package com.sec.etech.process.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sec.etech.common.constant.DBConstant;
import com.sec.etech.file.service.EtechWebUploaderService;
import com.sec.etech.process.mapper.SppRelFileMapper;
import com.sec.etech.process.model.SppRelFile;
import com.sec.etech.sys.util.DbUtil;
import org.openbpm.base.core.id.IdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class SppRelFileService extends ServiceImpl<SppRelFileMapper, SppRelFile> {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Resource
    private EtechWebUploaderService etechWebUploaderService;

    public void saveRelFile(Integer targetType, Long targetId, String fileId, String fileName) {
        String fileType = "1";
        if ("pdf".equalsIgnoreCase(FileUtil.getSuffix(fileName))) {
            fileType = "2";
        }
        SppRelFile sppRelFile = new SppRelFile();
        sppRelFile.setRelFileId(IdUtil.getUId());
        sppRelFile.setFileid(fileId);
        sppRelFile.setFilename(fileName);
        sppRelFile.setFileType(fileType);
        sppRelFile.setTargetType(targetType);
        sppRelFile.setTargetId(targetId);
        sppRelFile.setOrderby(this.getMaxOrderby(targetType, targetId, fileType));
        sppRelFile.setActive(1);
        super.save(sppRelFile);
    }

    private synchronized int getMaxOrderby(Integer targetType, Long targetId, String fileType) {
        String sql = "select max(orderby) maxNo from spp_rel_file where target_type=? and target_id=? and file_type=?";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, targetType, targetId, fileType);
        int orderBy = 0;
        if (list != null && list.size() > 0 && list.get(0).get("maxNo") != null) {
            orderBy = (int) list.get(0).get("maxNo");
        }
        return orderBy + 1;
    }

    /**
     * 获取附件
     *
     * @param target_id
     * @return
     */
    public List<Map<String, Object>> getAttachments(Long target_id, int target_type, boolean onlyPdf) {
        String sql = "SELECT t1.rel_file_id,t1.target_id,t1.step_id,t1.fileid,t2.name_,t1.orderby,t1.file_type " +
                "FROM spp_rel_file t1 LEFT JOIN sys_file t2 ON CONCAT(t1.fileid, '' ) = t2.id_ " +
                "WHERE t1.target_id = ? and t1.active =1 and t1.target_type = ? ";
        if (onlyPdf) {
            sql += "and t1.file_type = 2 ";
        }
        sql += " ORDER BY t1.orderby asc";
        return DbUtil.getJdbcTemplate(DBConstant.ETECH_SLAVE).queryForList(sql, target_id, target_type);
    }

    /**
     * 删除附件
     *
     * @param relFileId
     */
    public void delAttachment(Long relFileId) {
        SppRelFile sppRelFile = this.getById(relFileId);
        etechWebUploaderService.deleteFile(sppRelFile.getFileid(), false);
        sppRelFile.setActive(0);
        this.updateById(sppRelFile);
    }

    /**
     * 重排序 (只对pdf重排序)
     *
     * @param targetId
     * @param targetType
     * @param relFileIds
     */
    public void reorder(Long targetId, Integer targetType, List<String> relFileIds) {
        if (CollUtil.isEmpty(relFileIds)) {
            return;
        }
        List<SppRelFile> list = baseMapper.selectList(Wrappers.<SppRelFile>lambdaQuery()
                .eq(SppRelFile::getTargetId, targetId)
                .eq(SppRelFile::getTargetType, targetType)
                .eq(SppRelFile::getActive, 1)
                .eq(SppRelFile::getFileType, 2)
                .orderByAsc(SppRelFile::getOrderby)
        );
        if (CollUtil.isNotEmpty(list)) {
            for (SppRelFile sppRelFile : list) {
                int index = relFileIds.indexOf(sppRelFile.getRelFileId().toString());
                if (index > -1) {
                    sppRelFile.setOrderby(index + 1);
                }
            }
            this.updateBatchById(list);
        }
    }

    /**
     * 获取路线卡/工序卡 关联的文件
     *
     * @param targetId
     * @param targetType
     * @return
     */
    public List<SppRelFile> getRefFileList(Long targetId, Integer targetType) {
        return baseMapper.selectList(Wrappers.<SppRelFile>lambdaQuery()
                .eq(SppRelFile::getTargetId, targetId)
                .eq(SppRelFile::getTargetType, targetType)
                .eq(SppRelFile::getActive, 1)
                .orderByAsc(SppRelFile::getOrderby)
        );
    }
}
